package com.gonsin.gmessage.logic.render;

import com.github.xiaoymin.knife4j.core.util.CommonUtils;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.github.classgraph.utils.FileUtils;
import lombok.SneakyThrows;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 渲染成markdown
 */
public class MarkdownRender implements ISenderRender {

    public static final String MARKDOWN_SAMPLE = "# ${(note)!}\n" +
            "##### 版本号：${(version)!}\n" +
            "<#if senders??>\n" +
            "<#list senders as sender>\n" +
            "## ${(sender.note)!}\n" +
            "### 监听路径： \n" +
            "\n" +
            "- 安卓终端：**${(sender.topicUrl)!}**\n" +
            "- 网  页  端 ：**${(sender.topicUrlDot)!}**\n" +
            "- 嵌  入  式 ：**${(sender.topicUrl)!}**\n" +
            "- 后台模块：**${(sender.topicUrl)!}**\n" +
            "" +
            "### 接收内容样式： \n" +
            "~~~ json\n" +
            "${(sender.json)!}\n" +
            "~~~\n" +
            "<#if sender.summary??>${(sender.summary)!}</#if>\n" +
            "|参数|参数含义|是否必须|类型|例子\n" +
            "|-|-|-|-|-|\n" +
            "${(sender.parameterList)!}\n" +
            "<br>\n" +
            "\n" +
            "</#list>\n" +
            "</#if>\n";

    private Template template;

    @SneakyThrows
    public MarkdownRender(){
        BufferedReader reader=null;
//        File resource = ResourceUtils.getFile("classpath:gmessage/markdownTemplates/sample.md");
//        String content = new String(CommonUtils.readBytes(resource), StandardCharsets.UTF_8);

        Configuration conf = new Configuration(Configuration.VERSION_2_3_22);
        conf.setObjectWrapper(new BeansWrapperBuilder(Configuration.VERSION_2_3_22).build());
        template = new Template("templateName", new StringReader(MARKDOWN_SAMPLE), conf);
    }


    @Override
    public String render(MessageDescription model) {
        Writer out = new StringWriter();
        try {
            template.process(model, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String content = out.toString();
        return content;
    }
}
